<?php

/**
 * @author chenshubo
 * 商品列表清单查询
 */
namespace App\Service\OrderService\OrderInterfaceService;

use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Service\CommodityService\BbcBestGoodsService;
use App\Model\PssModel\TemplateDelivery;
use App\Service\AppService\SystemCacheConfigService;

class QueryGoodsLists extends BaseService
{    
    //默认分页大小限制
    const OFFSET_LIMIT      = 20 ;
    //最大页码限制
    const MAX_OFFSET_LIMITT = 100000;
    //缓存时间
    const CACHE_TIME        = 60;
    //最大分页量
    const MAX_PAGE_SIZE     = 100;
    
    /**
     * 查询订单物流单号
     */
    public function index( $param = [] ) 
    {
        $requestData = $param['requestData'];
        
        //处理分页参数
        $page       = $requestData['page'] ?? 0 ;
        $page       = is_numeric($page) && $page <= self::MAX_OFFSET_LIMITT ?  $page : self::MAX_OFFSET_LIMITT;
        
        //分页大小
        $pageSize   = $requestData['pageSize'] ?? self::OFFSET_LIMIT ;
        $limit      = is_numeric($pageSize) && $pageSize <= self::MAX_PAGE_SIZE ?  $pageSize : self::OFFSET_LIMIT;
        $page       = $page >= 1 ? $page -1 : $page;
        $offset = $limit * $page;
        $offset < 0 && $offset = 0;
        $limit <= 0 && $limit = self::OFFSET_LIMIT;
        
        $binfo = $param['binfo'];
        $bid = $binfo['bid'];
        $requestData['bid'] = $bid;
        $cacheKey   = md5(http_build_query($requestData));
        $cacheKey   = "web_goods_lists_{$bid}_".$cacheKey;
        $redis = $this->getRedisObj();
        $goodsLists = $redis->get($cacheKey);
        if( !empty($goodsLists) ) {
            $goodsLists = json_decode($goodsLists,true);
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'goodsLists' => $goodsLists
            ]);
        }
        
        //获取授权商品分页列表数据接口
        $query = [
            'bid'   => $bid,
            'page'  => $page,
            'limit' => $limit
        ];
        
        //获取默认运费模板
        $defaultTemplateInfo    = TemplateDelivery::instance()->getDefaultTemplateInfo();
        //获取毛利规则
        $goodsLevelConfig = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('goods_level');
        //价格模板利率
        $tplInfo = @json_decode($binfo['template_price_tpl'],true);
        $resQuery = BbcBestGoodsService::instance()->getBestGoodsPageList($query);
        $goodsLists = [];
        if( $resQuery['data'] ) {
            $pageDatas = $resQuery['data']['data'];
            $goodsLists = BbcBestGoodsService::instance()->getChannelPushGoodsByPriceTpl($binfo,$tplInfo,$pageDatas,$goodsLevelConfig,$defaultTemplateInfo);
        }
        
        //获取五层结构数据
        //更新查询结果到缓存
        $redis->set($cacheKey,json_encode($goodsLists),self::CACHE_TIME);
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'goodsLists' => $goodsLists
        ]);
    }
}